//
//  YNGroupAndDiscussion.m
//  Messenger
//
//  Created by iOS on 15/3/26.
//  Copyright (c) 2015年 YN-APP-iOS. All rights reserved.
//

#import "YNGroupAndDiscussion.h"
#import "XMPPIDTracker.h"
#import "YNUser.h"
#import "XMPPFramework.h"
#import "YNContactManager.h"
#import "YNIMTool.h"
#import "YNIMFrameworkMacro.h"

@interface YNGroupAndDiscussion()
@property (nonatomic, weak) id <YNXMPPprotocol> delegate;
@end

@implementation YNGroupAndDiscussion

- (instancetype)initWithDelegate:(id<YNXMPPprotocol>)delegate
{
    self.delegate = delegate;
    return [self initWithGroupDispatchQueue:NULL];
}

- (id)initWithGroupDispatchQueue:(dispatch_queue_t)queue
{
    if (self = [super initWithDispatchQueue:queue])
    {
        
    }
    return self;
}

- (BOOL)activate:(XMPPStream *)aXmppStream
{
    if ([super activate:aXmppStream])
    {
        xmppIDTracker = [[XMPPIDTracker alloc] initWithStream:xmppStream dispatchQueue:moduleQueue];
        
        return YES;
    }
    return NO;
}

- (void)deactivate
{
    dispatch_block_t block = ^{ @autoreleasepool {
        
        [xmppIDTracker removeAllIDs];
        xmppIDTracker = nil;
    
    }};
    
    if (dispatch_get_specific(moduleQueueTag))
    {
        block();
    }
    else
    {
        dispatch_sync(moduleQueue, block);
    }
    [super deactivate];
}

/**
 * 概述: 创建讨论组
 * @pram array 讨论组成员
 */
- (void)creatDiscussionWithUsers:(NSArray *)memberArray
{
    NSMutableArray *nameArray = [NSMutableArray array];
    NSMutableString *groupNameStr = [NSMutableString string];
    
    for (int i = 0; i < [memberArray count]; i++)
    {
        YNUser *user = [memberArray objectAtIndex:i];
        NSString *nameNo = user.userNo;
        
        [groupNameStr appendString:user.userName];
        
        [nameArray addObject:nameNo];
    }
    
    if (groupNameStr.length > 20)
    {
        NSString *subString = [groupNameStr substringWithRange:NSMakeRange(0, 20)];
        groupNameStr = nil;
        groupNameStr = [NSMutableString stringWithString:subString];
        
        [groupNameStr appendFormat:@"%@",@"..."];
    }
    
    //设置创建时间
    NSDate *sendDate=[NSDate date];
    
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    
    [dateformatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    
    NSString *locationString=[dateformatter stringFromDate:sendDate];
    
    //描述，该讨论组谁什么时间创建
    YNUser *currentUser = [YNContactManager queryCurrentUser];
    NSString *desc = [NSString stringWithFormat:@"%@创建于%@",currentUser.userName,locationString];
    
    [self creatGroupWithUsers:nameArray GroupType:kContact_DiscussionGropType GroupName:@"" NaturalName:groupNameStr Subject:groupNameStr desc:desc];
}

/**
 * 概述: 创建群
 * @pram array          群成员
 *       groupName      为群号,只能是字母、数字 (我也不晓得这是什么)
 *       naturalName    群名称 (必填)
 *       subject        群公告 (通常为nil)
 */
- (void)creatGroupWithUsers:(NSArray *)array GroupName:(NSString *)groupName NaturalName:(NSString *)naturalName subject:(NSString *)subject Desc:(NSString *)desc
{

    NSMutableArray *tempArray = [NSMutableArray array];
    
    for (int number = 0; number < array.count; number++)
    {
        YNUser *user = [array objectAtIndex:number];
        [tempArray addObject:user.userNo];
    }
    [self creatGroupWithUsers:array GroupType:kContact_UserGroupType GroupName:groupName NaturalName:naturalName Subject:subject desc:desc];
}

/**
 * 概述: 群和讨论组添加成员
 * @pram groupName 群或讨论组ID
 *       array     添加的成员列表
 */
- (void)addUserWithGroupName:(NSString *)groupName Users:(NSArray *)array
{
    dispatch_block_t block = ^{ @autoreleasepool{
        /*
         <iq id="URRYf-31" type="set" from="xiongshihui@m.com/Spark 2.6.3" to="admin@m.com"><req xmlns="com:yineng:group"><action></action><params>{"groupName":"","memberList":[]}}</params></req></iq>
         */
        NSXMLElement *req = [NSXMLElement elementWithName:@"req" xmlns:@"com:yineng:group"];
        NSXMLElement *action = [NSXMLElement elementWithName:@"action" numberValue:[NSNumber numberWithInt:3]];
        [req addChild:action];
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:groupName forKey:@"groupName"];
        
        NSMutableArray *tempArray = [NSMutableArray array];
        //debugLog(@"添加成员个数：%zd",[array count]);
        for (int number = 0; number < array.count; number++)
        {
            NSString *userNo = [array objectAtIndex:number];
            [tempArray addObject:userNo];
        }
        
        [dic setObject:tempArray forKey:@"memberList"];
        
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSXMLElement *params = [NSXMLElement elementWithName:@"params" stringValue:jsonString];
        [req addChild:params];
        
        XMPPJID *myJID = xmppStream.myJID;
        
        XMPPIQ *iq = [XMPPIQ iqWithType:@"set" elementID:[XMPPStream generateUUID]];
        [iq addAttributeWithName:@"frome" stringValue:myJID.description];
        [iq addAttributeWithName:@"to" stringValue:myJID.domain];
        [iq addChild:req];
        __block id myMulticastDelegate = _delegate;
        [xmppIDTracker addID:[iq elementID] block:^(XMPPIQ *iq, id <XMPPTrackingInfo> info){
            
            //接受返回信息
            /*
             <iq type="result" id="URRYf-31" from="admin@m.com" to="xiongshihui@m.com/Spark 2.6.3"><req xmlns="com:yineng:group "><action></action><resp>{"groupName":""}</resp><code>200</code></req></iq>
             */
            BOOL isSuccss = [[[iq elementForName:@"req"] elementForName:@"code"] stringValueAsInt] == 200 ? YES : NO;
            
            if (myMulticastDelegate && [myMulticastDelegate respondsToSelector:@selector(reciveAddGroupUserInfo:)])
            {
                [myMulticastDelegate reciveAddGroupUserInfo:isSuccss];
            }
            
            
        }timeout:10];
        [xmppStream sendElement:iq];
    
    }};
    
    if (dispatch_get_specific(moduleQueueTag)) {
        
        block();
        
    }else {
        
        dispatch_async(moduleQueue, block);
    }

    
}

/**
 * 概述: 退出群和讨论组
 * @pram groupName 群或讨论组ID
 */
- (void)leaveGourpWithGroupName:(NSString *)groupName
{
    dispatch_block_t block = ^{ @autoreleasepool{
    
        /*
         <iq id="URRYf-31" type="set" from="xiongshihui@m.com/Spark 2.6.3" to="admin@m.com"><req xmlns="com:yineng:group"><action></action><params>{"groupName":""}</params></req></iq>
         */
        NSXMLElement *req = [NSXMLElement elementWithName:@"req" xmlns:@"com:yineng:group"];
        NSXMLElement *action = [NSXMLElement elementWithName:@"action" numberValue:[NSNumber numberWithInt:5]];
        [req addChild:action];
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:groupName forKey:@"groupName"];
        
        
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSXMLElement *params = [NSXMLElement elementWithName:@"params" stringValue:jsonString];
        [req addChild:params];
        
        XMPPJID *myJID = xmppStream.myJID;
        
        XMPPIQ *iq = [XMPPIQ iqWithType:@"set" elementID:[XMPPStream generateUUID]];
        [iq addAttributeWithName:@"frome" stringValue:myJID.description];
        [iq addAttributeWithName:@"to" stringValue:myJID.domain];
        [iq addChild:req];
        __block id myMulticastDelegate = _delegate;
        [xmppIDTracker addID:[iq elementID] block:^(XMPPIQ *iq, id <XMPPTrackingInfo> info){
            
            BOOL isSuccss = NO;
            if (iq != nil)//iq不为空时
            {
                isSuccss = [[[iq elementForName:@"req"] elementForName:@"code"] stringValueAsInt] == 200 ? YES : NO;
            }
            else
            {
                isSuccss = NO;
                debugLog(@"返回iq为空");
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                if (myMulticastDelegate && [myMulticastDelegate respondsToSelector:@selector(reciveLeaveGroupInfo:)])
                {
                    [myMulticastDelegate reciveLeaveGroupInfo:isSuccss];
                }
                //退出讨论组的结果通知在‘YNMessagerManager’管理类里的自己退出讨论组的‘didReceivePresence:’回调里执行，不在这个iq回执结果里通知
            });
            
        }timeout:10.f];
        
        [xmppStream sendElement:iq];
        
    }};
    
    if (dispatch_get_specific(moduleQueueTag)) {
        
        block();
        
    }else {
        
        dispatch_async(moduleQueue, block);
    }
}

/**
 * 概述: 获取群信息及群成员
 * @pram groupName 群ID
 */
- (void)getGroupInfoWithGoupName:(NSString *)groupName
{
    if (groupName == nil)
    {
        groupName = @"";
    }
    
    dispatch_block_t block = ^{ @autoreleasepool {
        
        /*
         <iq id="URRYf-31" type="get" from="xiongshihui@m.com/Spark 2.6.3" to="admin@m.com"><req xmlns="com:yineng:group"><action></action><params>{"groupName":""}</params></req></iq>
         */
        
        //req
        NSXMLElement *req = [NSXMLElement elementWithName:@"req" xmlns:@"com:yineng:group"];
        
        
        //params
        NSDictionary *dic = [NSDictionary dictionaryWithObject:groupName forKey:@"groupName"];
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSXMLElement *params = [NSXMLElement elementWithName:@"params" stringValue:jsonString];
        [req addChild:params];
        NSXMLElement *action = [NSXMLElement elementWithName:@"action" numberValue:[NSNumber numberWithInt:8]];
        [req addChild:action];
        
        XMPPJID *myJid = xmppStream.myJID;
        //iq
        XMPPIQ *iq = [XMPPIQ iqWithType:@"get" elementID:[XMPPStream generateUUID]];
        [iq addAttributeWithName:@"from" stringValue:myJid.description];
        [iq addAttributeWithName:@"to" stringValue:myJid.domain];
        [iq addChild:req];
        __block id myMulticastDelegate = _delegate;
        [xmppIDTracker addID:[iq elementID] block:^(XMPPIQ *iq, id <XMPPTrackingInfo> info){
            
            //接受返回信息
            /*
             <iq type="result" id="URRYf-31" from="admin@m.com" to="xiongshihui@m.com/Spark 2.6.3"><req xmlns="com:yineng:group "><action></action><resp>{"groupList":[{"groupName":"","subject":"","desc":"","maxUsers":"","memberList":[{}{}]}]}</resp><code>200</code></req></iq>
             */
            
            
            if (iq != nil)//iq不为空时
            {
                NSXMLElement *req = [iq elementForName:@"req"];
                BOOL isSuccss = [[req elementForName:@"code"] stringValueAsInt] == 200 ? YES : NO;
                
                if (isSuccss)
                {
                    NSXMLElement *resp = [req elementForName:@"resp"];
                    
                    NSDictionary *dic = (NSDictionary*)[YNIMTool getJsonObjectFromJsonString:[resp stringValue]];
                    
                    if (dic!=nil)
                    {
                        if (dic)
                        {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                if (myMulticastDelegate && [myMulticastDelegate respondsToSelector:@selector(reciveGroupInfo:)])
                                {
                                    [myMulticastDelegate reciveGroupInfo:dic];
                                }
                            });
                        }
                        else
                        {
                            debugLog(@"返回数据为空");
                        }
                        
                    }
                    
                }
                else
                {
                    debugLog(@"获取群信息及群成员失败");
                }
                
            }
            else
            {
                debugLog(@"返回iq为空");
            }
            
        }timeout:10.f];
     
        
        [xmppStream sendElement:iq];
        
    }};
    
    if (dispatch_get_specific(moduleQueueTag)) {
        
        block();
        
    }else {
        
        dispatch_async(moduleQueue, block);
    }

}

/**
 获取项目组共享文件
 
 @param projectTeamName 项目组名称
 @param block 回调block  infoDic：json字典
 */
-(void)getFileOfProjectTeamShareWithProjectTeamName:(NSString*)projectTeamName completionBlock:(void(^)(BOOL isSucceed,NSDictionary *infoDic))block
{
    
}


/**
 * 概述: 获取群共享文件
 * @pram groupName 群ID
 */
- (void)getFileOfGroupShareWithGoupName:(NSString *)groupName
{
    if (groupName == nil)
    {
        groupName = @"";
    }
    
    dispatch_block_t block = ^{ @autoreleasepool {
        
        
        /*
         <iq id="URRYf-31" type="get" from="xiongshihui@m.com/Spark 2.6.3" to="admin@m.com"><req xmlns="com:yineng:group"><action></action><params>{"groupName":""}</params></req></iq>
         */
        
        //req
        NSXMLElement *req = [NSXMLElement elementWithName:@"req" xmlns:@"com:yineng:group"];
        
        
        //params
        NSDictionary *dic = [NSDictionary dictionaryWithObject:groupName forKey:@"groupName"];
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSXMLElement *params = [NSXMLElement elementWithName:@"params" stringValue:jsonString];
        [req addChild:params];
        NSXMLElement *action = [NSXMLElement elementWithName:@"action" numberValue:[NSNumber numberWithInt:10]];
        [req addChild:action];
        
        XMPPJID *myJid = xmppStream.myJID;
        //iq
        XMPPIQ *iq = [XMPPIQ iqWithType:@"get" elementID:[XMPPStream generateUUID]];
        [iq addAttributeWithName:@"from" stringValue:myJid.description];
        [iq addAttributeWithName:@"to" stringValue:myJid.domain];
        [iq addChild:req];
        __block id myMulticastDelegate = _delegate;
        [xmppIDTracker addID:[iq elementID] block:^(XMPPIQ *iq, id <XMPPTrackingInfo> info){
            
            //接受返回信息
 
            /*
             
             <iq type="result" id="URRYf-31" from="admin@m.com" to="xiongshihui@m.com/Spark 2.6.3"><req xmlns="com:yineng:group "><action></action><resp>{"groupName":"","fileList":[{"fileId":"","fileName":"","fileType":"","fileSize":"","owner":"","uploadTime":""}]}</resp><code>200</code></req></iq>
             
             */
            if (iq != nil)//iq不为空时
            {
                NSXMLElement *req = [iq elementForName:@"req"];
                BOOL isSuccss = [[req elementForName:@"code"] stringValueAsInt] == 200 ? YES : NO;
                
                if (isSuccss)
                {
                    NSXMLElement *resp = [req elementForName:@"resp"];
                    
                    NSDictionary *dic = (NSDictionary*)[YNIMTool getJsonObjectFromJsonString:[resp stringValue]];
                    
                    if (dic!=nil)//解析正确
                    {
                        if (dic)
                        {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                if (myMulticastDelegate && [myMulticastDelegate respondsToSelector:@selector(reciveFileInfoOfGroupShare:)])
                                {
                                    [myMulticastDelegate reciveFileInfoOfGroupShare:dic];
                                }
                            });
                        }
                        else
                        {
                            debugLog(@"返回数据为空");
                        }
                    
                    }
                    
                }
                else
                {
                    debugLog(@"获取群文件失败");
                }
               
            }
            else
            {
                debugLog(@"返回iq为空");
            }
            
            
        }timeout:10.f];
        
        
        [xmppStream sendElement:iq];
        
    }};
    
    if (dispatch_get_specific(moduleQueueTag)) {
        
        block();
        
    }else {
        
        dispatch_async(moduleQueue, block);
    }

}

/**
 * 概述: 获取一批用户的详细信息
 * @pram memberArray 用户ID数组
 */
- (void)getUserListWithUserNoList:(NSArray *)memberArray
{

    dispatch_block_t block = ^{ @autoreleasepool {
        
        
        /*
         <iq id="URRYf-31" type="get" from="xiongshihui@m.com/Spark 2.6.3" to="admin@m.com"><req xmlns="com:yineng:querydetail">
         <params>{"userNoList":["123","456"]}</params></req></iq>
         */
        
        //req
        NSXMLElement *req = [NSXMLElement elementWithName:@"req" xmlns:@"com:yineng:querydetail"];
        
        //params
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:memberArray forKey:@"userNoList"];
        [dic setObject:[NSNumber numberWithBool:YES] forKey:@"isUserNo"];
        
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSXMLElement *params = [NSXMLElement elementWithName:@"params" stringValue:jsonString];
        [req addChild:params];
        
        
        XMPPJID *myJid = xmppStream.myJID;
        //iq
        XMPPIQ *iq = [XMPPIQ iqWithType:@"get" elementID:[XMPPStream generateUUID]];
        [iq addAttributeWithName:@"from" stringValue:myJid.description];
        [iq addAttributeWithName:@"to" stringValue:myJid.domain];
        [iq addChild:req];
        __block id myMulticastDelegate = _delegate;
        [xmppIDTracker addID:[iq elementID] block:^(XMPPIQ *iq, id <XMPPTrackingInfo> info){
            
            //接受返回信息
            /*
             <iq type="result" id="URRYf-31" from="admin@m.com" to="xiongshihui@m.com/Spark 2.6.3"><req xmlns="com:yineng: querydetail"><resp>[{"createTime":0,"dayOfBirth":"" ,"email":"","gender":0,"headUrl":"","joinTime":"","post":"","removeTag":0,"signature":"","telephone":"","userName":"xiongshihui","userNo":"","userType":0}]</resp><code>200</code></req></iq>
             
             */
            
            if (iq != nil)
            {
                NSXMLElement *req = [iq elementForName:@"req"];
                BOOL isSuccss = [[req elementForName:@"code"] stringValueAsInt] == 200 ? YES : NO;
                
                if (isSuccss)
                {
                    NSXMLElement *resp = [req elementForName:@"resp"];
                    
                    NSArray *array = (NSArray*)[YNIMTool getJsonObjectFromJsonString:[resp stringValue]];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (array != nil)
                        {
                            if (myMulticastDelegate && [myMulticastDelegate respondsToSelector:@selector(reciveUserList:userListDictionary:)])
                            {
                                [myMulticastDelegate reciveUserList:YES userListDictionary:array];
                            }
                        }
                        else
                        {
                            if (myMulticastDelegate && [myMulticastDelegate respondsToSelector:@selector(reciveUserList:userListDictionary:)])
                            {
                                [myMulticastDelegate reciveUserList:NO userListDictionary:nil];
                            }
                            
                        }
                    });
                }
                else
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (myMulticastDelegate && [myMulticastDelegate respondsToSelector:@selector(reciveUserList:userListDictionary:)])
                        {
                            [myMulticastDelegate reciveUserList:NO userListDictionary:nil];
                        }
                    });
                }
            }
            else
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (myMulticastDelegate && [myMulticastDelegate respondsToSelector:@selector(reciveUserList:userListDictionary:)])
                    {
                        [myMulticastDelegate reciveUserList:NO userListDictionary:nil];
                    }
                });
            }
            
            
        }timeout:5.f];
        
        [xmppStream sendElement:iq];
        
    }};
    
    if (dispatch_get_specific(moduleQueueTag)) {
        
        block();
        
    }else {
        
        dispatch_async(moduleQueue, block);
    }



}

/**
 * 概述: 删除群共享文件
 */
- (void)deleteGroupShareFile:(NSString *)fileId
{
    if (fileId == nil)
    {
        fileId = @"";
    }
    
    dispatch_block_t block = ^{ @autoreleasepool {
        
        
        /*
         <iq id="URRYf-31" type="set" from="xiongshihui@m.com/Spark 2.6.3" to="admin@m.com"><req xmlns="com:yineng:group"><action></action><params>{"fileId":""}</params></req></iq>
         */
        
        //req
        NSXMLElement *req = [NSXMLElement elementWithName:@"req" xmlns:@"com:yineng:group"];

        //params
        NSDictionary *dic = [NSDictionary dictionaryWithObject:fileId forKey:@"fileId"];
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSXMLElement *params = [NSXMLElement elementWithName:@"params" stringValue:jsonString];
        [req addChild:params];
        NSXMLElement *action = [NSXMLElement elementWithName:@"action" numberValue:[NSNumber numberWithInt:11]];
        [req addChild:action];
        
        XMPPJID *myJid = xmppStream.myJID;
        //iq
        XMPPIQ *iq = [XMPPIQ iqWithType:@"set" elementID:[XMPPStream generateUUID]];
        [iq addAttributeWithName:@"from" stringValue:myJid.description];
        [iq addAttributeWithName:@"to" stringValue:myJid.domain];
        [iq addChild:req];
        __block id myMulticastDelegate = _delegate;
        [xmppIDTracker addID:[iq elementID] block:^(XMPPIQ *iq, id <XMPPTrackingInfo> info){
            
            //接受返回信息
            /*
             <iq type="result" id="URRYf-31" from="admin@m.com" to="xiongshihui@m.com/Spark 2.6.3"><req xmlns="com:yineng:group "><action></action><resp>{}</resp><code>200</code></req></iq>
             
             */
            dispatch_async(dispatch_get_main_queue(), ^{
                if (iq != nil)
                {
                    NSXMLElement *req = [iq elementForName:@"req"];
                    BOOL isSuccss = [[req elementForName:@"code"] stringValueAsInt] == 200 ? YES : NO;
                    
                    if (isSuccss)
                    {
                        NSXMLElement *resp = [req elementForName:@"resp"];
                        
                        NSDictionary *dic = (NSDictionary*)[YNIMTool getJsonObjectFromJsonString:[resp stringValue]];
            
                        if (dic != nil)
                        {
                            if (myMulticastDelegate && [myMulticastDelegate respondsToSelector:@selector(didFinishedDeleteShareGroupFile:)])
                            {
                                [myMulticastDelegate didFinishedDeleteShareGroupFile:fileId];
                            }
                        }
                        else
                        {
                            if (myMulticastDelegate && [myMulticastDelegate respondsToSelector:@selector(failedDeleteShareGroupFile:)])
                            {
                                [myMulticastDelegate failedDeleteShareGroupFile:nil];
                            }
                            
                        }
                    }
                    else
                    {
                        if (myMulticastDelegate && [myMulticastDelegate respondsToSelector:@selector(failedDeleteShareGroupFile:)])
                        {
                            [myMulticastDelegate failedDeleteShareGroupFile:nil];
                        }
                    }
                }
                else
                {
                    if (myMulticastDelegate && [myMulticastDelegate respondsToSelector:@selector(failedDeleteShareGroupFile:)])
                    {
                        [myMulticastDelegate failedDeleteShareGroupFile:nil];
                    }
                    
                }
            });
            
            
        }timeout:5.f];
        
        [xmppStream sendElement:iq];
        
    }};
    
    if (dispatch_get_specific(moduleQueueTag)) {
        
        block();
        
    }else {
        
        dispatch_async(moduleQueue, block);
    }


}

- (void)modifyGroupSubject:(NSString *)subjuct GroupName:(NSString *)groupName
{

    if (groupName == nil)
    {
        groupName = @"";
    }
    
    dispatch_block_t block = ^{ @autoreleasepool {
        
        /*
         <iq id="URRYf-31" type="set" from="xiongshihui@m.com/Spark 2.6.3" to="admin@m.com"><req xmlns="com:yineng:group"><action></action><params>{"groupName":"","subject":""…}</params></req></iq>
         */
        
        //req
        NSXMLElement *req = [NSXMLElement elementWithName:@"req" xmlns:@"com:yineng:group"];
        
        NSXMLElement *action = [NSXMLElement elementWithName:@"action" numberValue:[NSNumber numberWithInt:2]];
        [req addChild:action];
        //params
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        
        [dic setObject:groupName forKey:@"groupName" ];
        [dic setObject:subjuct forKey:@"subject"];
        
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSXMLElement *params = [NSXMLElement elementWithName:@"params" stringValue:jsonString];
        [req addChild:params];
        
        
        XMPPJID *myJid = xmppStream.myJID;
        //iq
        XMPPIQ *iq = [XMPPIQ iqWithType:@"set" elementID:[xmppStream generateUUID]];
        [iq addAttributeWithName:@"from" stringValue:myJid.description];
        [iq addAttributeWithName:@"to" stringValue:myJid.domain];
        [iq addChild:req];
        __block id myMulticastDelegate = _delegate;
        [xmppIDTracker addID:[iq elementID] block:^(XMPPIQ *iq, id <XMPPTrackingInfo> info){
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (iq != nil)
                {
                    NSXMLElement *req = [iq elementForName:@"req"];
                    BOOL isSuccss = [[req elementForName:@"code"] stringValueAsInt] == 200 ? YES : NO;
                    
                    if (isSuccss)
                    {
                        NSXMLElement *resp = [req elementForName:@"resp"];
                        NSDictionary *tempDic = (NSDictionary*)[YNIMTool getJsonObjectFromJsonString:[resp stringValue]];
                        if (myMulticastDelegate && [myMulticastDelegate respondsToSelector:@selector(reciveModifyGroupSubject:resultDictionary:)])
                        {
                            [myMulticastDelegate reciveModifyGroupSubject:isSuccss resultDictionary:tempDic];
                        }
                    }
                    else
                    {
                        if (myMulticastDelegate && [myMulticastDelegate respondsToSelector:@selector(reciveModifyGroupSubject:resultDictionary:)])
                        {
                            [myMulticastDelegate reciveModifyGroupSubject:isSuccss resultDictionary:nil];
                        }
                    }
                }
                else
                {
                    if (myMulticastDelegate && [myMulticastDelegate respondsToSelector:@selector(reciveModifyGroupSubject:resultDictionary:)])
                    {
                        [myMulticastDelegate reciveModifyGroupSubject:NO resultDictionary:nil];
                    }
                
                }
            });
            
        }timeout:10];
        
        
        [xmppStream sendElement:iq];
        
    }};
    
    if (dispatch_get_specific(moduleQueueTag)) {
        
        block();
        
    }else {
        
        dispatch_async(moduleQueue, block);
    }
}


/**
 * 概述: 获取讨论组信息及讨论组成员
 * @pram groupName 讨论组ID
 */
- (void)getDiscussionInfoWithDiscussionName:(NSString *)DiscussionName
{
    if (DiscussionName == nil)
    {
        DiscussionName = @"";
    }
    
    dispatch_block_t block = ^{ @autoreleasepool{
        
        /*
         <iq id="URRYf-31" type="get" from="xiongshihui@m.com/Spark 2.6.3" to="admin@m.com"><req xmlns="com:yineng:group"><action></action><params>{"groupName":""}</params></req></iq>
         */
        
        //req
        NSXMLElement *req = [NSXMLElement elementWithName:@"req" xmlns:@"com:yineng:group"];
        
        
        //params
        NSDictionary *dic = [NSDictionary dictionaryWithObject:DiscussionName forKey:@"groupName"];
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSXMLElement *params = [NSXMLElement elementWithName:@"params" stringValue:jsonString];
        [req addChild:params];
        NSXMLElement *action = [NSXMLElement elementWithName:@"action" numberValue:[NSNumber numberWithInt:9]];
        [req addChild:action];
        XMPPJID *myJid = xmppStream.myJID;
        //iq
        XMPPIQ *iq = [XMPPIQ iqWithType:@"get" elementID:[XMPPStream generateUUID]];
        [iq addAttributeWithName:@"from" stringValue:myJid.description];
        [iq addAttributeWithName:@"to" stringValue:myJid.domain];
        [iq addChild:req];
        __block id myMulticastDelegate = _delegate;
        [xmppIDTracker addID:[iq elementID] block:^(XMPPIQ *iq, id <XMPPTrackingInfo> info){
            
            //接受返回信息
            
            /*
             <iq type="result" id="URRYf-31" from="admin@m.com" to="xiongshihui@m.com/Spark 2.6.3"><req xmlns="com:yineng:group "><action></action><resp>{"groupList":[{"groupName":"","subject":"","desc":"","maxUsers":"","memberList":[{}{}]}]}</resp><code>200</code></req></iq>
             */
            NSXMLElement *req = [iq elementForName:@"req"];
            NSXMLElement *resp = [req elementForName:@"resp"];
            
            NSDictionary *dic = (NSDictionary*)[YNIMTool getJsonObjectFromJsonString:[resp stringValue]];
           
            dispatch_async(dispatch_get_main_queue(), ^{
                if (myMulticastDelegate && [myMulticastDelegate respondsToSelector:@selector(reciveDiscussionInfo:)])
                {
                     [myMulticastDelegate reciveDiscussionInfo:dic];
                }
            });
            
        }timeout:10];
        
        [xmppStream sendElement:iq];
        
    }};
    
    if (dispatch_get_specific(moduleQueueTag))
    {
        block();
    }
    else
    {
        dispatch_async(moduleQueue, block);
    }

}

/**
 * 概述: 获取项目组信息及项目组成员
 * @pram groupName 项目组ID
 */
- (void)getProjectTeamInfoWithTeamName:(NSString *)ProjectTeamName
{
    if (ProjectTeamName == nil)
    {
        ProjectTeamName = @"";
    }
    
    dispatch_block_t block = ^{ @autoreleasepool{
        
        /*
         <iq id="URRYf-31" type="get" from="xiongshihui@m.com/Spark 2.6.3" to="admin@m.com"><req xmlns="com:yineng:group"><action></action><params>{"groupName":""}</params></req></iq>
         */
        
        //req
        NSXMLElement *req = [NSXMLElement elementWithName:@"req" xmlns:@"com:yineng:group"];
        
        
        //params
        NSDictionary *dic = [NSDictionary dictionaryWithObject:ProjectTeamName forKey:@"groupName"];
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSXMLElement *params = [NSXMLElement elementWithName:@"params" stringValue:jsonString];
        [req addChild:params];
        NSXMLElement *action = [NSXMLElement elementWithName:@"action" numberValue:[NSNumber numberWithInt:9]];
        [req addChild:action];
        XMPPJID *myJid = xmppStream.myJID;
        //iq
        XMPPIQ *iq = [XMPPIQ iqWithType:@"get" elementID:[XMPPStream generateUUID]];
        [iq addAttributeWithName:@"from" stringValue:myJid.description];
        [iq addAttributeWithName:@"to" stringValue:myJid.domain];
        [iq addChild:req];
        __block id myMulticastDelegate = _delegate;
        [xmppIDTracker addID:[iq elementID] block:^(XMPPIQ *iq, id <XMPPTrackingInfo> info){
            
            //接受返回信息
            
            /*
             <iq type="result" id="URRYf-31" from="admin@m.com" to="xiongshihui@m.com/Spark 2.6.3"><req xmlns="com:yineng:group "><action></action><resp>{"groupList":[{"groupName":"","subject":"","desc":"","maxUsers":"","memberList":[{}{}]}]}</resp><code>200</code></req></iq>
             */
            NSXMLElement *req = [iq elementForName:@"req"];
            NSXMLElement *resp = [req elementForName:@"resp"];
            
            NSDictionary *dic = (NSDictionary*)[YNIMTool getJsonObjectFromJsonString:[resp stringValue]];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (myMulticastDelegate && [myMulticastDelegate respondsToSelector:@selector(reciveProjectTeamInfo:)])
                {
                    [myMulticastDelegate reciveProjectTeamInfo:dic];
                }
            });
            
        }timeout:10];
        
        [xmppStream sendElement:iq];
        
    }};
    
    if (dispatch_get_specific(moduleQueueTag))
    {
        block();
    }
    else
    {
        dispatch_async(moduleQueue, block);
    }
    
}

/**
 * 概述: 创建群或讨论组
 * @pram array          成员列表
 *       groupType      为1表示群,2表示讨论组
 *       groupName      为群号,只能是字母、数字(通常为nil)
 *       naturalName    群名称(必填)
 *       subject        群公告(通常为nil)
 *       desc           群描述(通常为nil)
 */
- (void)creatGroupWithUsers:(NSArray *)array GroupType:(int)grouptype GroupName:(NSString *)groupName NaturalName:(NSString *)naturalName Subject:(NSString *)subject desc:(NSString *)desc
{
    WEAKSELF
    dispatch_block_t block = ^{ @autoreleasepool {
        /**
         <iq id="URRYf-31" type="set" from="xiongshihui@m.com/Spark 2.6.3" to="admin@m.com"><req xmlns="com:yineng:group"><action></action><params>{"subject":""…}</params></req></iq>
         */
        NSXMLElement *req = [NSXMLElement elementWithName:@"req" xmlns:@"com:yineng:group"];
        NSXMLElement *action = [NSXMLElement elementWithName:@"action" numberValue:[NSNumber numberWithInt:1]];
        [req addChild:action];
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:groupName forKey:@"groupName"];
        [dic setObject:naturalName forKey:@"naturalName"];
        [dic setObject:subject forKey:@"subject"];
        [dic setObject:desc forKey:@"desc"];
        [dic setObject:[NSNumber numberWithInt:grouptype] forKey:@"groupType"];
        [dic setObject:array forKey:@"memberList"];
        
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSXMLElement *params = [NSXMLElement elementWithName:@"params" stringValue:jsonString];
        [req addChild:params];
        
        XMPPJID *myJID = xmppStream.myJID;
        
        XMPPIQ *iq = [XMPPIQ iqWithType:@"set" elementID:[XMPPStream generateUUID]];
        [iq addAttributeWithName:@"from" stringValue:myJID.description];
        [iq addAttributeWithName:@"to" stringValue:myJID.domain];
        [iq addChild:req];
        
//        __block id myMulticastDelegate = _delegate;
        [xmppIDTracker addID:[iq elementID] block:^(XMPPIQ *iq, id <XMPPTrackingInfo> info){
            
            NSInteger code = [[[iq elementForName:@"req"] elementForName:@"code"] stringValueAsInt];
            BOOL isSuccess = code == 200 ? YES : NO;
            if (isSuccess)
            {
                NSDictionary *resultDic = (NSDictionary*)[YNIMTool getJsonObjectFromJsonString:[[[iq elementForName:@"req"] elementForName:@"resp"] stringValue]];
                
                NSString *groupNo = [resultDic objectForKey:@"groupName"];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    if ([weakSelf.delegate respondsToSelector:@selector(createGroupWithRequestFinished:naturalName:)])
                    {
                        [weakSelf.delegate createGroupWithRequestFinished:groupNo naturalName:naturalName];
                    }
                });
            }
            else
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if ([weakSelf.delegate respondsToSelector:@selector(createGroupWithRequestFailed:)])
                    {
                        [weakSelf.delegate createGroupWithRequestFailed:[YNGroupAndDiscussion errorCodeParseWithCodeString:code]];
                    }
                });
            }
           

            
        }timeout:10];
        [xmppStream sendElement:iq];
    
    }};
    if (dispatch_get_specific(moduleQueueTag)) {
        
        block();
        
    }else {
        
        dispatch_async(moduleQueue, block);
    }
}

#pragma mark XMPPStream Delegate
- (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq
{
    
    
    NSXMLElement *req = [iq elementForName:@"req"];
    if (req)
    {
        if([iq isSetIQ])
        {
            
        }
        else if([iq isResultIQ])
        {
            dispatch_block_t block = ^{ @autoreleasepool{

                [xmppIDTracker invokeForID:[iq elementID] withObject:iq];
            }};
            
            if (dispatch_get_specific(moduleQueueTag))
            {
                block();
            }
            else
            {
                dispatch_async(moduleQueue, block);
            }
        }
        return YES;
    }
    return NO;
}
/**
 *  @brief  根据错误代码返回错误原因
 *
 *  @param errorcode 错误代码
 *
 *  @return 错误原因
 */
+ (NSString *)errorCodeParseWithCodeString:(NSInteger)errorcode
{
    NSString *errorString;
    
    switch (errorcode)
    {
        case 200:
        {
            errorString = @"处理成功";
        }
            break;
            
        case 202:
        {
            errorString = @"非法操作";
        }
            break;
            
        case 203:
        {
            errorString = @"参数错误";
        }
            break;
            
        case 204:
        {
            errorString = @"未授权、鉴权失败";
        }
            break;
            
        case 205:
        {
            errorString = @"密码错误";
        }
            break;
            
        case 206:
        {
            errorString = @"数据不可修改";
        }
            break;
            
        case 207:
        {
            errorString = @"不支持的操作";
        }
            break;
            
        case 301:
        {
            errorString = @"根节点不存在";
        }
            break;
            
        case 302:
        {
            errorString = @"根节点已存在";
        }
            break;
            
        case 303:
        {
            errorString = @"父级节点不存在";
        }
            break;
            
        case 304:
        {
            errorString = @"组织机构已存在";
        }
            break;
            
        case 305:
        {
            errorString = @"组织机构不存在";
        }
            break;
            
        case 306:
        {
            errorString = @"组织机构不为空,表示其下还有子部门或者员工";
        }
            break;
            
        case 401:
        {
            errorString = @"用户已存在";
        }
            break;
            
        case 402:
        {
            errorString = @"用户不存在";
        }
            break;
            
        case 601:
        {
            errorString = @"超出群用户上限";
        }
            break;
            
        case 602:
        {
            errorString = @"群或讨论组已存在";
        }
            break;
            
        case 603:
        {
            errorString = @"群公告为空";
        }
            break;
            
        case 604:
        {
            errorString = @"权限不够";
        }
            break;
            
        case 605:
        {
            errorString = @"群或讨论组不存在";
        }
            break;
            
        case 606:
        {
            errorString = @"群或讨论组超出上限";
        }
            break;
            
        case 701:
        {
            errorString = @"文件是空的";
        }
            break;
            
        case 702:
        {
            errorString = @"文件不存在";
        }
            break;
            
        case 802:
        {
            errorString = @"更新的项目不存在";
        }
            break;

            
        default:
        {
        
            errorString = @"连接失败，请稍后再试";
        }
            break;
    }


    return errorString;

}
@end
